// 无障碍功能核心服务
// 提供屏幕阅读器支持、键盘导航、高对比度模式等功能

import { reactive, provide, inject } from 'vue';
import { storage } from '../../utils/storage';
import { globalConfig } from '../../config/globalConfig';

// 无障碍配置状态
const accessibilityState = reactive({
  // 屏幕阅读器相关配置
  screenReader: {
    // 是否启用屏幕阅读器支持
    enabled: true,
    // 朗读速度 (0.5 - 2.0)
    speed: 1.0,
    // 语音类型
    voice: 'default',
    // 是否自动朗读页面内容
    autoRead: false,
    // 是否朗读元素描述
    readDescriptions: true
  },
  
  // 键盘导航配置
  keyboardNavigation: {
    // 是否启用键盘导航
    enabled: true,
    // 快捷键配置
    shortcuts: {
      // 导航相关快捷键
      navigate: {
        nextItem: 'ArrowRight',
        prevItem: 'ArrowLeft',
        nextSection: 'ArrowDown',
        prevSection: 'ArrowUp',
        home: 'Home',
        end: 'End'
      },
      // 操作相关快捷键
      actions: {
        activate: 'Enter',
        select: 'Space',
        openMenu: 'Alt+F',
        search: 'Ctrl+F',
        settings: 'Alt+S',
        help: 'F1'
      }
    },
    // 是否显示焦点指示器
    showFocus: true,
    // 焦点指示器样式
    focusStyle: 'default' // default, high-visibility
  },
  
  // 视觉辅助配置
  visualAids: {
    // 高对比度模式
    highContrast: false,
    // 字体大小缩放 (0.8 - 2.0)
    fontSizeScale: 1.0,
    // 行高调整 (1.0 - 2.0)
    lineHeight: 1.5,
    // 颜色反转模式
    invertColors: false,
    // 减少动画效果
    reducedMotion: false,
    // 内容放大功能
    zoom: {
      enabled: true,
      defaultLevel: 1.0,
      maxLevel: 3.0
    }
  },
  
  // 交互辅助配置
  interactionAids: {
    // 触摸目标放大
    largeTargets: false,
    // 长按激活
    longPress: {
      enabled: false,
      duration: 1000
    },
    // 声音反馈
    soundFeedback: {
      enabled: true,
      volume: 0.7
    },
    // 震动反馈
    vibrationFeedback: {
      enabled: true,
      intensity: 0.5
    },
    // 输入辅助
    inputAssistance: {
      enabled: false,
      predictText: true,
      autoCapitalize: true,
      autoCorrect: true
    }
  },
  
  // 内容辅助配置
  contentAids: {
    // 朗读时高亮显示
    highlightAsRead: true,
    // 标点符号朗读
    readPunctuation: false,
    // 图片描述优先
    imageDescriptions: true,
    // 表格辅助
    tableAssistance: true,
    // 代码辅助
    codeAssistance: false,
    // 数学公式辅助
    mathAssistance: false
  },
  
  // 无障碍测试模式
  testingMode: {
    // 是否启用测试模式
    enabled: false,
    // 显示无障碍问题
    showIssues: false,
    // 显示无障碍树
    showTree: false
  },
  
  // 无障碍评分
  accessibilityScore: {
    // 当前页面评分
    currentPage: 0,
    // 整体应用评分
    overall: 0,
    // 上次测试时间
    lastTested: null
  }
});

// 无障碍服务类
class AccessibilityService {
  constructor() {
    this.state = accessibilityState;
    this.listeners = new Map();
    this.announcementsQueue = [];
    this.isAnnouncing = false;
    this.keyboardHandlers = new Map();
    this.initialize();
  }
  
  // 初始化无障碍服务
  initialize() {
    // 从存储加载配置
    this.loadConfig();
    
    // 应用无障碍设置
    this.applySettings();
    
    // 设置键盘事件监听
    this.setupKeyboardListeners();
    
    // 初始化屏幕阅读器
    this.initializeScreenReader();
    
    // 监听全局配置变化
    this.listenToGlobalConfig();
  }
  
  // 从存储加载配置
  loadConfig() {
    try {
      const savedConfig = storage.get('accessibilityConfig');
      if (savedConfig && typeof savedConfig === 'object') {
        this.mergeConfig(savedConfig, this.state);
      }
    } catch (error) {
      console.error('加载无障碍配置失败:', error);
    }
  }
  
  // 保存配置到存储
  saveConfig() {
    try {
      storage.set('accessibilityConfig', this.state, 365 * 24 * 60); // 保存一年
    } catch (error) {
      console.error('保存无障碍配置失败:', error);
    }
  }
  
  // 合并配置
  mergeConfig(source, target) {
    Object.keys(source).forEach(key => {
      if (target[key] && typeof target[key] === 'object' && !Array.isArray(target[key])) {
        this.mergeConfig(source[key], target[key]);
      } else {
        target[key] = source[key];
      }
    });
  }
  
  // 应用无障碍设置
  applySettings() {
    // 应用视觉辅助设置
    this.applyVisualSettings();
    
    // 应用交互辅助设置
    this.applyInteractionSettings();
    
    // 应用内容辅助设置
    this.applyContentSettings();
    
    // 应用键盘导航设置
    this.applyKeyboardSettings();
    
    // 保存配置
    this.saveConfig();
  }
  
  // 应用视觉辅助设置
  applyVisualSettings() {
    const { highContrast, fontSizeScale, lineHeight, invertColors, reducedMotion } = this.state.visualAids;
    const root = document.documentElement;
    
    // 应用高对比度模式
    if (highContrast) {
      root.classList.add('high-contrast');
      // 同步到全局配置
      globalConfig.setHighContrast(true);
    } else {
      root.classList.remove('high-contrast');
      // 同步到全局配置
      globalConfig.setHighContrast(false);
    }
    
    // 应用字体大小缩放
    if (fontSizeScale !== 1.0) {
      root.style.fontSize = `${fontSizeScale * 100}%`;
      // 同步到全局配置
      globalConfig.setFontSizeScale(fontSizeScale);
    }
    
    // 应用行高调整
    if (lineHeight !== 1.5) {
      root.style.lineHeight = lineHeight;
    }
    
    // 应用颜色反转
    if (invertColors) {
      root.classList.add('invert-colors');
    } else {
      root.classList.remove('invert-colors');
    }
    
    // 应用减少动画
    if (reducedMotion) {
      root.classList.add('reduce-motion');
      // 同步到全局配置
      globalConfig.setAnimationsEnabled(false);
    } else {
      root.classList.remove('reduce-motion');
      // 同步到全局配置
      globalConfig.setAnimationsEnabled(true);
    }
  }
  
  // 应用交互辅助设置
  applyInteractionSettings() {
    const { largeTargets, soundFeedback, vibrationFeedback } = this.state.interactionAids;
    const root = document.documentElement;
    
    // 应用触摸目标放大
    if (largeTargets) {
      root.classList.add('large-targets');
    } else {
      root.classList.remove('large-targets');
    }
    
    // 设置声音反馈标志
    root.dataset.soundFeedback = soundFeedback.enabled ? 'true' : 'false';
    
    // 设置震动反馈标志
    root.dataset.vibrationFeedback = vibrationFeedback.enabled ? 'true' : 'false';
  }
  
  // 应用内容辅助设置
  applyContentSettings() {
    const { highlightAsRead, readPunctuation, imageDescriptions } = this.state.contentAids;
    const root = document.documentElement;
    
    // 设置内容辅助标志
    root.dataset.highlightAsRead = highlightAsRead ? 'true' : 'false';
    root.dataset.readPunctuation = readPunctuation ? 'true' : 'false';
    root.dataset.imageDescriptions = imageDescriptions ? 'true' : 'false';
  }
  
  // 应用键盘导航设置
  applyKeyboardSettings() {
    const { showFocus, focusStyle } = this.state.keyboardNavigation;
    const root = document.documentElement;
    
    // 设置焦点指示器
    if (showFocus) {
      root.classList.add('show-focus');
      root.dataset.focusStyle = focusStyle;
    } else {
      root.classList.remove('show-focus');
    }
  }
  
  // 设置键盘事件监听
  setupKeyboardListeners() {
    if (!this.state.keyboardNavigation.enabled) return;
    
    // 键盘导航处理
    const handleKeyDown = (event) => {
      // 检查是否按下快捷键
      const shortcut = this.getActiveShortcut(event);
      if (shortcut) {
        // 阻止默认行为
        event.preventDefault();
        event.stopPropagation();
        
        // 触发快捷键处理
        this.handleShortcut(shortcut);
      }
      
      // 通知键盘事件
      this.notifyKeyboardEvent(event);
    };
    
    // 绑定键盘事件
    document.addEventListener('keydown', handleKeyDown);
    
    // 保存清理函数
    this.cleanupFunctions = this.cleanupFunctions || [];
    this.cleanupFunctions.push(() => {
      document.removeEventListener('keydown', handleKeyDown);
    });
  }
  
  // 获取激活的快捷键
  getActiveShortcut(event) {
    const { shortcuts } = this.state.keyboardNavigation;
    const allShortcuts = { ...shortcuts.navigate, ...shortcuts.actions };
    
    // 检查单键快捷键
    if (!event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) {
      for (const [action, key] of Object.entries(allShortcuts)) {
        if (key === event.key) {
          return { action, key };
        }
      }
    }
    
    // 检查组合键快捷键
    for (const [action, key] of Object.entries(allShortcuts)) {
      if (key.includes('+')) {
        const parts = key.split('+').map(k => k.trim());
        let match = true;
        
        // 检查修饰键
        if (parts.includes('Ctrl') && !event.ctrlKey) match = false;
        if (parts.includes('Alt') && !event.altKey) match = false;
        if (parts.includes('Shift') && !event.shiftKey) match = false;
        if (parts.includes('Meta') && !event.metaKey) match = false;
        
        // 检查普通键
        const normalKey = parts.find(k => !['Ctrl', 'Alt', 'Shift', 'Meta'].includes(k));
        if (normalKey && normalKey !== event.key) match = false;
        
        if (match) {
          return { action, key };
        }
      }
    }
    
    return null;
  }
  
  // 处理快捷键
  handleShortcut(shortcut) {
    const { action } = shortcut;
    
    // 触发快捷键处理
    if (this.keyboardHandlers.has(action)) {
      this.keyboardHandlers.get(action).forEach(handler => {
        try {
          handler(shortcut);
        } catch (error) {
          console.error(`快捷键 ${action} 处理失败:`, error);
        }
      });
    }
    
    // 通知快捷键事件
    this.notifyShortcutEvent(shortcut);
  }
  
  // 注册键盘快捷键处理器
  registerKeyboardHandler(action, handler) {
    if (!this.keyboardHandlers.has(action)) {
      this.keyboardHandlers.set(action, new Set());
    }
    this.keyboardHandlers.get(action).add(handler);
    
    // 返回取消注册函数
    return () => {
      this.unregisterKeyboardHandler(action, handler);
    };
  }
  
  // 取消注册键盘快捷键处理器
  unregisterKeyboardHandler(action, handler) {
    if (this.keyboardHandlers.has(action)) {
      this.keyboardHandlers.get(action).delete(handler);
    }
  }
  
  // 初始化屏幕阅读器
  initializeScreenReader() {
    // 检查浏览器是否支持 SpeechSynthesis API
    this.speechSupported = 'speechSynthesis' in window;
    
    if (this.speechSupported) {
      // 预加载语音
      this.preloadVoices();
    } else {
      console.warn('当前浏览器不支持语音合成功能');
    }
  }
  
  // 预加载语音
  preloadVoices() {
    const voices = window.speechSynthesis.getVoices();
    if (voices.length > 0) {
      this.availableVoices = voices;
    } else {
      // 等待语音加载完成
      window.speechSynthesis.onvoiceschanged = () => {
        this.availableVoices = window.speechSynthesis.getVoices();
      };
    }
  }
  
  // 朗读文本
  speak(text, options = {}) {
    if (!this.state.screenReader.enabled || !this.speechSupported) {
      return Promise.resolve();
    }
    
    return new Promise((resolve, reject) => {
      try {
        // 创建语音实例
        const utterance = new SpeechSynthesisUtterance(text);
        
        // 应用配置
        utterance.rate = options.speed || this.state.screenReader.speed;
        utterance.volume = options.volume || 1.0;
        utterance.pitch = options.pitch || 1.0;
        
        // 设置语音
        if (this.availableVoices && this.availableVoices.length > 0) {
          const voice = this.availableVoices.find(v => 
            v.name.toLowerCase().includes((options.voice || this.state.screenReader.voice).toLowerCase())
          );
          if (voice) {
            utterance.voice = voice;
          }
        }
        
        // 设置回调
        utterance.onend = () => {
          this.isAnnouncing = false;
          this.processAnnouncementQueue();
          resolve();
        };
        
        utterance.onerror = (error) => {
          this.isAnnouncing = false;
          console.error('语音合成错误:', error);
          reject(error);
        };
        
        // 如果当前正在朗读，将新的朗读任务加入队列
        if (this.isAnnouncing) {
          this.announcementsQueue.push({ utterance, resolve, reject });
        } else {
          // 立即开始朗读
          this.isAnnouncing = true;
          window.speechSynthesis.speak(utterance);
        }
      } catch (error) {
        console.error('创建语音实例失败:', error);
        reject(error);
      }
    });
  }
  
  // 处理朗读队列
  processAnnouncementQueue() {
    if (this.announcementsQueue.length > 0) {
      const nextAnnouncement = this.announcementsQueue.shift();
      this.isAnnouncing = true;
      window.speechSynthesis.speak(nextAnnouncement.utterance);
    }
  }
  
  // 停止当前朗读
  stopSpeaking() {
    if (this.speechSupported) {
      window.speechSynthesis.cancel();
      this.isAnnouncing = false;
      this.announcementsQueue = [];
    }
  }
  
  // 暂停朗读
  pauseSpeaking() {
    if (this.speechSupported) {
      window.speechSynthesis.pause();
    }
  }
  
  // 恢复朗读
  resumeSpeaking() {
    if (this.speechSupported) {
      window.speechSynthesis.resume();
    }
  }
  
  // 公告文本（简短通知）
  announce(text) {
    return this.speak(text, { priority: 'high' });
  }
  
  // 监听全局配置变化
  listenToGlobalConfig() {
    // 监听主题变化
    globalConfig.onThemeChange((theme) => {
      // 如果启用了高对比度模式，同步到无障碍配置
      if (this.state.visualAids.highContrast !== theme.highContrast) {
        this.setState('visualAids.highContrast', theme.highContrast);
      }
      
      // 如果启用了字体大小缩放，同步到无障碍配置
      if (this.state.visualAids.fontSizeScale !== theme.fontSizeScale) {
        this.setState('visualAids.fontSizeScale', theme.fontSizeScale);
      }
      
      // 如果禁用了动画，同步到无障碍配置
      if (this.state.visualAids.reducedMotion !== !theme.animationsEnabled) {
        this.setState('visualAids.reducedMotion', !theme.animationsEnabled);
      }
    });
  }
  
  // 设置状态值（支持点号路径）
  setState(path, value) {
    const parts = path.split('.');
    let obj = this.state;
    
    // 遍历路径直到倒数第二个属性
    for (let i = 0; i < parts.length - 1; i++) {
      if (!obj[parts[i]]) {
        obj[parts[i]] = {};
      }
      obj = obj[parts[i]];
    }
    
    // 设置最终属性
    obj[parts[parts.length - 1]] = value;
    
    // 应用设置
    this.applySettings();
  }
  
  // 切换屏幕阅读器支持
  toggleScreenReader() {
    this.state.screenReader.enabled = !this.state.screenReader.enabled;
    this.applySettings();
    return this.state.screenReader.enabled;
  }
  
  // 切换高对比度模式
  toggleHighContrast() {
    this.state.visualAids.highContrast = !this.state.visualAids.highContrast;
    this.applySettings();
    return this.state.visualAids.highContrast;
  }
  
  // 切换减少动画模式
  toggleReducedMotion() {
    this.state.visualAids.reducedMotion = !this.state.visualAids.reducedMotion;
    this.applySettings();
    return this.state.visualAids.reducedMotion;
  }
  
  // 调整字体大小
  adjustFontSize(scale) {
    // 限制在合理范围内
    const validScale = Math.max(0.8, Math.min(2.0, scale));
    this.state.visualAids.fontSizeScale = validScale;
    this.applySettings();
    return validScale;
  }
  
  // 调整朗读速度
  adjustSpeechSpeed(speed) {
    // 限制在合理范围内
    const validSpeed = Math.max(0.5, Math.min(2.0, speed));
    this.state.screenReader.speed = validSpeed;
    this.applySettings();
    return validSpeed;
  }
  
  // 注册无障碍事件监听器
  on(event, callback) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, new Set());
    }
    this.listeners.get(event).add(callback);
    
    // 返回取消注册函数
    return () => {
      this.off(event, callback);
    };
  }
  
  // 取消注册无障碍事件监听器
  off(event, callback) {
    if (this.listeners.has(event)) {
      this.listeners.get(event).delete(callback);
    }
  }
  
  // 通知无障碍事件
  notify(event, data) {
    if (this.listeners.has(event)) {
      this.listeners.get(event).forEach(callback => {
        try {
          callback(data);
        } catch (error) {
          console.error(`调用 ${event} 监听器失败:`, error);
        }
      });
    }
  }
  
  // 通知键盘事件
  notifyKeyboardEvent(event) {
    this.notify('keyboardEvent', event);
  }
  
  // 通知快捷键事件
  notifyShortcutEvent(shortcut) {
    this.notify('shortcutEvent', shortcut);
  }
  
  // 获取无障碍配置
  getConfig() {
    return { ...this.state };
  }
  
  // 重置无障碍配置
  resetConfig() {
    Object.assign(this.state, {
      screenReader: {
        enabled: true,
        speed: 1.0,
        voice: 'default',
        autoRead: false,
        readDescriptions: true
      },
      keyboardNavigation: {
        enabled: true,
        shortcuts: {
          navigate: {
            nextItem: 'ArrowRight',
            prevItem: 'ArrowLeft',
            nextSection: 'ArrowDown',
            prevSection: 'ArrowUp',
            home: 'Home',
            end: 'End'
          },
          actions: {
            activate: 'Enter',
            select: 'Space',
            openMenu: 'Alt+F',
            search: 'Ctrl+F',
            settings: 'Alt+S',
            help: 'F1'
          }
        },
        showFocus: true,
        focusStyle: 'default'
      },
      visualAids: {
        highContrast: false,
        fontSizeScale: 1.0,
        lineHeight: 1.5,
        invertColors: false,
        reducedMotion: false,
        zoom: {
          enabled: true,
          defaultLevel: 1.0,
          maxLevel: 3.0
        }
      },
      interactionAids: {
        largeTargets: false,
        longPress: {
          enabled: false,
          duration: 1000
        },
        soundFeedback: {
          enabled: true,
          volume: 0.7
        },
        vibrationFeedback: {
          enabled: true,
          intensity: 0.5
        },
        inputAssistance: {
          enabled: false,
          predictText: true,
          autoCapitalize: true,
          autoCorrect: true
        }
      },
      contentAids: {
        highlightAsRead: true,
        readPunctuation: false,
        imageDescriptions: true,
        tableAssistance: true,
        codeAssistance: false,
        mathAssistance: false
      },
      testingMode: {
        enabled: false,
        showIssues: false,
        showTree: false
      },
      accessibilityScore: {
        currentPage: 0,
        overall: 0,
        lastTested: null
      }
    });
    
    // 清除存储并应用新配置
    storage.remove('accessibilityConfig');
    this.applySettings();
  }
  
  // 清理资源
  cleanup() {
    // 执行所有清理函数
    if (this.cleanupFunctions) {
      this.cleanupFunctions.forEach(fn => fn());
    }
    
    // 停止朗读
    this.stopSpeaking();
  }
}

// 创建无障碍服务实例
const accessibilityService = new AccessibilityService();

// 提供无障碍服务给Vue组件
export function provideAccessibility() {
  provide('accessibility', accessibilityService);
}

// 在组件中注入无障碍服务
export function useAccessibility() {
  const service = inject('accessibility');
  if (!service) {
    throw new Error('无障碍服务未提供，请在应用根组件中调用 provideAccessibility');
  }
  return service;
}

// 导出无障碍服务实例
export { accessibilityService };